import os
from flask import Flask, request, send_file, jsonify
from dotenv import load_dotenv
import requests
import tempfile

load_dotenv()
ZHIPU_KEY = os.getenv("ZHIPU-KEY")

app = Flask(__name__)

@app.route('/api/zhipu-tts', methods=['POST'])
def zhipu_tts():
    data = request.json
    text = data.get("input")
    model = data.get("model", "default")
    voice = data.get("voice", "default")
    # ...其他参数...
    if not text:
        return jsonify({"error": "Missing input text"}), 400

    # 伪代码，实际API参数请查阅智谱清言官方文档
    headers = {"Authorization": f"Bearer {ZHIPU_KEY}"}
    payload = {
        "text": text,
        "model": model,
        "voice": voice,
        # ...其他参数...
    }
    resp = requests.post("https://api.zhipu.com/v1/tts", json=payload, headers=headers)
    if resp.status_code != 200:
        return jsonify({"error": "TTS failed"}), 500

    with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmpfile:
        tmpfile.write(resp.content)
        return send_file(tmpfile.name, mimetype='audio/mp3', as_attachment=True, download_name='speech.mp3')

if __name__ == "__main__":
    app.run(port=5002)
